package com.sqllite.springbootsqlitejdbc.datainit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class DataInitializer {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @PostConstruct
    public void init() {
        try {
            initUserTable();
        } catch (Exception e) {
            log.error("初始化异常",e);
        }
    }

    private void initUserTable() {

        String createTableSql = "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)";
        dropAndCreateTable("users",createTableSql);

        // 插入测试数据
        String insertSql = "INSERT INTO users (name, email) VALUES (?, ?)";
        jdbcTemplate.update(insertSql, "John Doe", "john.doe@example.com");
        System.out.println("Data inserted successfully.");
    }

    private void dropAndCreateTable(String tableName,String createTableSql) {
        String dropTableSql = "DROP TABLE IF EXISTS "+tableName;
        jdbcTemplate.execute(dropTableSql);
        System.out.println("Table '"+tableName+"' dropped successfully.");
        jdbcTemplate.execute(createTableSql);
        System.out.println("Table '"+tableName+"' created successfully.");
    }
}
